<template>
    <div class="manage">
        <!-- <h1>i m p2</h1>
        <p>{{ noticesInfo }}</p> -->
        <el-dialog
        :title="dialogtitle"
        :visible.sync="dialogVisible" 
        :before-close="handleClose"
        width="50%">

            <el-form ref="form" :rules="rules" :model="form" label-width="80px" :inline="true" >
                <!-- prop属性用于与rules中的rule绑定 -->
                <el-form-item label="公告名称" prop="name">
                    <el-input placeholder="请输入公告名称" v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="公告详细信息" prop="detail">
                    <el-input placeholder="请输入详细信息" v-model="form.detail"></el-input>
                </el-form-item>
            </el-form>
            
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="submit">确 定</el-button>
            </span>
        </el-dialog>
        <!-- +新增按钮 -->
        <div class="manage-header">
            <el-button @click="handleAdd" type="primary">
                + 新增
            </el-button>
            <!-- 搜索表单 -->
            <el-form>

            </el-form>
        </div>

        <div class="common-table">
            <el-table
            height="90%"
            :data="noticesInfo"
            stripe
            :row-style="{height: '100px'}"
            style="width: 100%">
                <el-table-column
                    prop="_id"
                    label="公告ID">
                </el-table-column>
                <el-table-column
                    prop="name"
                    label="公告名称">
                </el-table-column>
                <el-table-column
                    prop="detail"
                    label="详细信息">
                </el-table-column>
                <el-table-column
                    prop="time"
                    label="时间"
                    :formatter="formatDate">
                </el-table-column>
                <el-table-column
                    prop="operation"
                    label="操作"
                    min-width="100px">
                    <template slot-scope="scope">
                            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                            <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pager">
                <el-pagination
                    layout="prev, pager, next"
                    :total="this.total"
                    @current-change="handlePage">
                </el-pagination>
            </div>
        </div>
    </div>
</template>

<script>
export default{
    name:'PageTwo',
    data(){
        return{
            //noticesInfo中总条数
            total:0,
            pageData:{
                pageSize: 10,
                currentPage : 1
            },
            noticesInfo:[],
            db:'',
            dialogtitle:"新增公告",
            tempObj:'',
            form:{
                name:'',
                detail:''
            },
            empty_form:{
                name:'',
                detail:''
            },
            //加上了时间戳的表单
            add_time_form:{
                name:'',
                detail:'',
                time:''
            },
            rules:{
                name:[
                    {required:true , message:'请输入公告名称'}
                ],
                detail:[
                    {required:true , message:'请输入公告详细信息'}
                ]

            },

            count : 1,
            dialogVisible:false,
            dialogtitle:"新增公告",
            modaltype:0//0新增，1编辑，标记弹窗状态
        }
    },
    methods:{
        initdb(){
            let that = this
            var c1 = new that.$cloud.Cloud({
                 //必填，表示是未登录模式
                identityless: true,
                //资源方 AppID
                resourceAppid: 'wx3a07f3c2fa333336',
                //资源方环境 ID
                resourceEnv: 'ayaka557-2gh3t7jm380b9701',
            })
            c1.init()
            console.log('c1',c1);
            //获取云数据库信息
            this.db = c1.database();
            console.log('db',this.db)
        },
        getWxNotices(){
            //封装一下分页查询
            this.getNoticesData(this.pageData.pageSize,this.pageData.currentPage)
        },
        getNoticesData(pageSize,currentPage){
            // 分页查询数据
            this.db.collection('notices').skip(pageSize*(currentPage - 1)).limit(pageSize).get()
                .then(res => {
                    this.noticesInfo = res.data
                    console.log('notices', this.noticesInfo)
                    this.db.collection('notices').count()
                        .then(res => {
                            console.log('total',res);
                            this.total = res.total
                        })
                        .catch(err => {
                            console.log('err',err);
                            
                        })
                    console.log('count',this.total);
                    
                })
                .catch(err => {
                    console.log(err);
                });
        },
        // 日期格式化
        formatDate(row, column) {
            // 获取单元格数据
            let data = row[column.property]
            if(data == null) {
                return null
            }
            let dt = new Date(data)
            let year = dt.getFullYear();
            let month = (dt.getMonth() + 1).toString().padStart(2, '0');
            let day = dt.getDate().toString().padStart(2, '0');
            let hours = dt.getHours().toString().padStart(2, '0');
            let minutes = dt.getMinutes().toString().padStart(2, '0');
            let seconds = dt.getSeconds().toString().padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        handleAdd(){
            //显示调用去掉bug
            // this.handleClose()
            //修改弹窗状态
            this.modaltype = 0//新增
            this.dialogtitle = "新增公告"
            //显示弹窗
            this.dialogVisible = true
        },
        handleClose(){
            this.$refs.form.resetFields()
            console.log("关闭弹窗，reset success")
            console.log("关闭后表单",this.form)
            this.dialogVisible = false
        },
        handleEdit(row){
            console.log("当前准备进行修改的行数据",row)
            //先修改弹窗的模式与标题，再显示弹窗
            this.modaltype = 1
            this.dialogtitle = " 修改公告信息"
            this.dialogVisible = true

            //不能直接赋值，不然直接修改了数据，需要点击确认才能修改
            //利用obj存储row中冗余的id项以及其余可能项，并传入obj的row进行修改
            //不使用this.obj =  row是因为这样两个变量会指向同一块地址，实际上是同一个变量的两个引用
            //回显
            this.tempObj = JSON.parse(JSON.stringify(row));
            this.form = {
                name:this.tempObj.name,
                detail:this.tempObj.detail
            }


        },
        handleDelete(row){
            console.log("deleteRowId",row._id)
            this.$confirm('此操作将永久删除该公告, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {//用户点击了确认按钮
                // console.log('我要删除');
                this.db.collection('notices').doc(row._id).remove()
                .then(() => {
                    console.log('Notice deleted successfully');

                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                        });
                    // 更新通知列表
                    this.getWxNotices();
                })
                .catch(err => {
                    console.error('Error deleting notice: ', err)
                    this.$message({
                        type: 'info',
                        message: '未知原因删除失败'
                    });       
                });

            }).catch(() => {//用户点击了取消按钮
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        submit(){
            this.$refs.form.validate((valid) => {
                //如果数据不完整，valid为false
                if(valid){
                    console.log(this.form);
                    //this.form是data,this.$refs.form是真正的表单
                    if(this.modaltype === 0){
                       //对后端发送增加请求......
                        this.add_time_form.name = this.form.name
                        this.add_time_form.detail = this.form.detail
                        this.add_time_form.time = new Date()
                        console.log('addForm',this.add_time_form)
                        this.db.collection('notices').add({data:this.add_time_form})  
                            .then(() => {
                                console.log('Notice added successfully');
                                // 更新通知列表
                                this.getWxNotices()
                            })
                            .catch(err => {
                                console.error('Error adding notice: ', err);
                            });
                         
                    }else{//修改
                        //对后端修改增加请求......
                        this.add_time_form.name = this.form.name
                        this.add_time_form.detail = this.form.detail
                        this.add_time_form.time = new Date()
                        console.log('Updateform',this.add_time_form)

                        this.db.collection('notices').doc(this.tempObj._id).update({data:this.add_time_form})
                            .then(() => {
                                console.log('Notice deleted successfully');
                                this.$message({
                                    type: 'success',
                                    message: '修改成功!'
                                    });
                                // 更新通知列表
                                this.getWxNotices();
                            })
                            .catch(err => {
                                console.error('Error deleting notice: ', err)
                                this.$message({
                                    type: 'info',
                                    message: '未知原因修改失败'
                                });       
                            });
                    }
                    this.handleClose()
                }
                else{
                    //do nothing
                }
            })
        },
        cancel(){
            this.handleClose()
        },
        handlePage(currentPage){
            //当点击分页栏的时候，传入页面号
            console.log(currentPage)
            this.pageData.currentPage = currentPage
            this.getWxNotices()
        }

    },
    mounted(){
        this.initdb()
        this.getWxNotices()
    }
}
</script>

<style lang="less">
.manage{
    height: 100%;
    .common-table{
        position: relative;
        height: calc(100% - 62px);
        .pager{
        position: absolute;
        bottom: 0;
        right: 20px;
        }
    }
    
}
</style>